﻿using Microsoft.Xna.Framework;

namespace jvox
{
    class Camera : GameComponent
    {
        public Vector3 position;
        public float leftrightRot = MathHelper.PiOver2;
        public float updownRot = -MathHelper.Pi / 10.0f;

        public Matrix view;
        public Matrix projection;
        public float fieldOfView = MathHelper.PiOver4;
        public float aspectRatio;

        public Camera(Game game, Vector3 startPosition)
            : base(game)
        {
            this.position = startPosition;
        }

        public override void Initialize()
        {
            base.Initialize();
        }

        public override void Update(GameTime gameTime)
        {
            aspectRatio = (float)Game.GraphicsDevice.Viewport.Width / (float)Game.GraphicsDevice.Viewport.Height;
            projection = Matrix.CreatePerspectiveFieldOfView(fieldOfView, aspectRatio, 1.0f, 1000.0f);
            UpdateViewMatrix();
            base.Update(gameTime);
        }

        protected void UpdateViewMatrix()
        {
            Matrix cameraRotation = Matrix.CreateRotationX(updownRot) * Matrix.CreateRotationY(leftrightRot);

            Vector3 cameraOriginalTarget = new Vector3(0, 0, -1);
            Vector3 cameraRotatedTarget = Vector3.Transform(cameraOriginalTarget, cameraRotation);
            Vector3 cameraFinalTarget = position + cameraRotatedTarget;

            Vector3 cameraOriginalUpVector = new Vector3(0, 1, 0);
            Vector3 cameraRotatedUpVector = Vector3.Transform(cameraOriginalUpVector, cameraRotation);
            
            view = Matrix.CreateLookAt(position, cameraFinalTarget, cameraRotatedUpVector);
        }
    }
}
